
#include <windows.h>
#include <stdio.h>

#include "../PEWork.h"

BOOL ReadFileAt( char *path, DWORD offset, void *buf, int bufsize, OPTIONAL int *pnReadResult=NULL, OPTIONAL int *LastError=NULL );

int main(int argc, char* argv[])
{
	pework pe;

	if( argc < 2 )
	{
		printf( "%s target file\n", argv[0] );
		return -1;
	}


	if( pe.Open( argv[1] ) == FALSE )
	{
		puts( "not pe" );
		return -1;
	}


	printf( "ep : 0x08%x\n", pe.GetEPRva() + pe.GetImageBase() );
	printf( "imagebase : 0x%08x\n", pe.GetImageBase() );
	BYTE buf[0x20];
	int rw;
	ReadFileAt( argv[1], pe.GetEPRaw(), (void*)buf, 0x20, &rw );
	printf( "ep buffer : \n" );
	for( int i = 0; i < rw; i ++ )
	{
		printf( "%02x ", buf[i] );
		if( ( ( i + 1 ) % 0x10 ) == 0 )
			puts( "" );
	}

	return 0;
}



BOOL ReadFileAt( char *path, DWORD offset, void *buf, int bufsize, OPTIONAL int *pnReadResult, OPTIONAL int *LastError )
{
	BOOL result = TRUE;
	HANDLE hf = INVALID_HANDLE_VALUE;
	int readresult;

	if( LastError != NULL )
	{
		*LastError = 0;
	}

	hf = CreateFile( path, 
					 GENERIC_READ, 
					 FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
					 NULL,
					 OPEN_EXISTING,
					 0, 
					 NULL );
	if( hf == INVALID_HANDLE_VALUE )
	{
		result = FALSE;
		if( LastError != NULL )
			*LastError = GetLastError();

		goto _END;
	}

	SetFilePointer( hf, offset, NULL, FILE_BEGIN );

	if( ReadFile( hf, buf, bufsize, (LPDWORD)&readresult, NULL ) == FALSE || readresult == 0 )
	{
		result = FALSE;
		if( LastError != NULL )
			*LastError = GetLastError();

		goto _END;
	}

	if( pnReadResult != NULL )
		*pnReadResult = readresult;

_END:

	if( hf != INVALID_HANDLE_VALUE )
		CloseHandle( hf );

	return result;

}